const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const User = require('../../models/user');
const { hashPassword, comparePassword } = require('../../utils/auth');
const AuthService = require('../../services/auth');

const JWT_SECRET = 'h5_secret';  // H5专用密钥，建议放在环境变量中

// H5用户登录
router.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body;
    const result = await AuthService.login(username, password);
    
    // 检查用户角色
    if (result.user.role !== 'h5') {
      return res.status(403).json({
        code: 403,
        message: '无权限访问H5端'
      });
    }
    
    res.status(200).json({
      code: 200,
      data: result
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: error.message
    });
  }
});

// H5用户注册
router.post('/register', async (req, res) => {
  try {
    // 添加h5角色
    const userData = {
      ...req.body,
      role: 'h5'
    };
    const result = await AuthService.register(userData);
    
    res.status(200).json({
      code: 200,
      data: result
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: error.message
    });
  }
});

// H5退出登录
router.post('/logout', async (req, res) => {
  try {
    res.status(200).json({
      code: 200,
      message: '退出成功'
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '退出失败'
    });
  }
});

// 获取当前用户信息
router.get('/current', async (req, res) => {
  try {
    const user = await User.findById(req.user.id).select('-password');
    
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在'
      });
    }

    res.status(200).json({
      code: 200,
      data: user
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: error.message
    });
  }
});

module.exports = router; 